﻿using System;

namespace CardPlay.Model.GameModel.Actions
{
    public class MovePileAction : GameAction, IPileAction
    {
        public MovePileAction(CardGame cardGame, RemovePileAction pickup, PartLocation to) : base(cardGame, to)
        {
            Guard.Against<ArgumentNullException>(pickup == null, "pickup");
        
            _pickupAction = pickup;
            _dropAction = new AddCardsAction(cardGame, to, PileBeingMoved);
        }

        public MovePileAction(CardGame cardGame, PartLocation from, PartLocation to) : base(cardGame, to)
        {
            _pickupAction = new RemovePileAction(cardGame, from);
            _dropAction = new AddCardsAction(cardGame, to, PileBeingMoved);
        }
        
        public PartLocation FromLocation
        {
            get
            {
                return _pickupAction.Location;
            }
        }
        
        public CardPile SourcePile
        {
            get
            {
                return CardGame.PileAt(_pickupAction.Location);
            }
        }

        public CardPile TargetPile
        {
            get
            {
                return CardGame.PileAt(_dropAction.Location);
            }
        }

        public CardPile PileBeingMoved
        {
            get
            {
                return _executed ? _dropAction.PileBeingAdded : _pickupAction.PileBeingRemoved;
            }
        }

        protected override void OnExecute()
        {
            _pickupAction.Execute();
            _dropAction.Execute();

            _executed = true;
        }

        protected override void OnReverse()
        {
            _dropAction.Reverse();
            _pickupAction.Reverse();

            _executed = false;
        }

        private readonly RemovePileAction _pickupAction;
        private readonly AddCardsAction _dropAction;

        private bool _executed;
    }
}
